﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;

namespace FoundationLib.Web.Mvc.Filters
{
	/// <summary>
	/// Represents an MVC action filter enforcing requests to be sent over a secure connection (SSL).
	/// </summary>
	public class RequireSsl : ActionFilterAttribute
	{
		/// <see cref="ActionFilterAttribute.OnActionExecuting(ActionExecutionContext)"/>
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			HttpRequestBase request = filterContext.HttpContext.Request;
			HttpResponseBase response = filterContext.HttpContext.Response;

			if (!request.IsSecureConnection && !request.IsLocal)
			{
				UriBuilder ub = new UriBuilder(request.Url);
				ub.Scheme = Uri.UriSchemeHttps;
				ub.Port = 443;
				string url = ub.Uri.ToString();

				if (!response.IsRequestBeingRedirected)
					response.Redirect(url, true);
			}

			base.OnActionExecuting(filterContext);
		}
	}
}
